package com.fw.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;

import javax.validation.constraints.NotBlank;
import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class JWTUtils {

    private static final String SECRET = "James";


    //创建token插入数据库
    public static String createToken(String userId, long time){
        try{
            System.out.println(userId);
            Date date = new Date(System.currentTimeMillis() + time);
            Algorithm algorithm = Algorithm.HMAC256(SECRET);
            Map<String, Object> header = new HashMap<>(2);
            header.put("typ", "JWT");
            header.put("alg", "HS256");
            String token = JWT.create()
                    .withHeader(header)
                    .withClaim("userId", userId)
                    .withExpiresAt(date)
                    .sign(algorithm);
            return token;
        }catch (UnsupportedEncodingException e){
            return null;
        }
    }

    //请求获取token对应用户信息
    public static String getUserId(@NotBlank String token){
        //解码获取token中存的userId
        DecodedJWT jwt = JWT.decode(token);
        String userId = jwt.getClaim("userId").asString();
        return userId;
    }
}
